Page({
  data: {
    searchValue: '',
    searchHistory: [],
    hotSearches: [
      '中心广场停车场',
      '商业街停车场',
      '地下停车场',
      '临时停车'
    ],
    searchResults: []
  },

  onLoad() {
    // 获取搜索历史
    const history = wx.getStorageSync('parkingSearchHistory') || []
    this.setData({ searchHistory: history })
  },

  // 输入搜索内容
  onInput(e) {
    this.setData({
      searchValue: e.detail.value
    })
  },

  // 确认搜索
  onSearch() {
    const { searchValue, searchHistory } = this.data
    if (!searchValue.trim()) return

    // 保存搜索历史
    const newHistory = [searchValue, ...searchHistory.filter(item => item !== searchValue)]
    if (newHistory.length > 10) newHistory.pop()
    
    this.setData({ searchHistory: newHistory })
    wx.setStorageSync('parkingSearchHistory', newHistory)

    // TODO: 调用搜索API
    this.getSearchResults(searchValue)
  },

  // 点击搜索历史或热门搜索
  onSearchItem(e) {
    const { value } = e.currentTarget.dataset
    this.setData({ searchValue: value }, () => {
      this.onSearch()
    })
  },

  // 清空搜索历史
  clearHistory() {
    wx.showModal({
      title: '提示',
      content: '确定清空搜索历史吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({ searchHistory: [] })
          wx.removeStorageSync('parkingSearchHistory')
        }
      }
    })
  },

  // 获取搜索结果
  getSearchResults(keyword) {
    // 模拟搜索API调用
    const results = [
      {
        id: 1,
        name: '地下停车场A区',
        address: '负一层A区',
        availableSpots: 50,
        totalSpots: 100
      },
      {
        id: 2,
        name: '地面停车场B区',
        address: '商业广场B区',
        availableSpots: 20,
        totalSpots: 80
      }
    ]
    
    this.setData({
      searchResults: results.filter(item => 
        item.name.toLowerCase().includes(keyword.toLowerCase()) ||
        item.address.toLowerCase().includes(keyword.toLowerCase())
      )
    })
  }
}) 